<template>
  <div>
    <h1>防抖，节流</h1>
    <input type="text" @input="inputChange" v-model="inputVal" />
    <div class="drag" draggable @dragstart="dragstart" @drag="drag">可拖拽</div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

let inputVal = ref('')
const inputChange = debounce(() => {
  console.log(123)
}, 1000)

// 防抖
function debounce(fn: Function, delay: number = 500) {
  let timer = null

  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      //   fn.apply(this, arguments)
      fn()
      timer = null
    }, delay)
  }
}
function dragstart() {
  console.log('tuo')
}
const drag = throttle(function () {
  console.log(999)
})

function throttle(fn, delay = 500) {
  let timer = null
  return function () {
    if (timer) return
    timer = setTimeout(() => {
      fn()
      timer = null
    }, delay)
  }
}
</script>

<style scoped lang="scss">
.drag {
  width: 100px;
  height: 100px;
  border: 1px solid rebeccapurple;
}
</style>
